﻿@page "/tests/repeater"
@using System.Collections.ObjectModel

<Row>
    <Column ColumnSize="ColumnSize.IsFull.OnMobile.IsHalf.OnTablet">
        <Card Margin="Margin.Is4.OnY">
            <CardHeader>
                <CardTitle>Repeater</CardTitle>
            </CardHeader>
            <CardBody>
                <Field Horizontal JustifyContent="JustifyContent.End">
                    <FieldLabel ColumnSize="ColumnSize.Is6">
                        <Buttons>
                            <Button Color="Color.Primary" Clicked="@(() => items.Add( items.Count + 1 ) )">Add</Button>
                            <Button Color="Color.Warning" Disabled="@(items.Count == 0)" Clicked="@(() => items.RemoveAt( items.Count - 1 ))">Remove</Button>
                            <Button Color="Color.Danger" Clicked="@(() => items.Clear())">Clear</Button>
                            <Button Color="Color.Secondary" Disabled="@(items.Count == 0)" Clicked="ShuffleList">Shuffle</Button>
                        </Buttons>
                    </FieldLabel>
                    <FieldBody ColumnSize="ColumnSize.Is6">
                        <Dropdown>
                            <DropdownToggle Color="Color.Primary">
                                Updating dropdown
                            </DropdownToggle>
                            <DropdownMenu>
                                <Repeater Items="@items">
                                    <DropdownItem>@context</DropdownItem>
                                </Repeater>
                            </DropdownMenu>
                        </Dropdown>
                    </FieldBody>
                </Field>
                <Field Horizontal JustifyContent="JustifyContent.End">
                    <FieldBody ColumnSize="ColumnSize.Is12">
                        <ul>
                            <Repeater Items="@items">
                                <li style="@GetColor( context )">@context</li>
                            </Repeater>
                        </ul>
                    </FieldBody>
                </Field>
            </CardBody>
        </Card>
    </Column>
</Row>

@code {
    private ObservableCollection<int> items { get; } = new( Enumerable.Range( 1, 4 ) );
    private Random random = new();

    private void ShuffleList()
    {
        var maxIndex = items.Count - 1;

        if ( maxIndex == -1 )
            return;

        var orgPos = random.Next( maxIndex );
        var newPos = random.Next( maxIndex );

        items.Move( orgPos, newPos );
    }

    private static string GetColor( int number )
    {
        const string letters = "0123456789ABCDEF";

        var color = "";

        for ( var i = 0; i < 6; i++ )
        {
            color += letters[( 3 * number + i ) % letters.Length];
        }

        return $"color: #{color}";
    }
}